package com.leyou.item.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.leyou.common.pojo.PageResult;
import com.leyou.item.mapper.BrandMapper;
import com.leyou.item.pojo.Brand;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.List;


@Service
public class BrandService {

    @Autowired
    private BrandMapper brandMapper;

    //分页查询品牌信息
    public PageResult<Brand> queryBrandByPageAndSort(Integer page, Integer rows, String sortBy, Boolean desc, String key) {
        //开始分页
        PageHelper.startPage(page,rows);
        //通过example对象设置查询条件
        Example example = new Example(Brand.class);
        Example.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotBlank(key)) {
            //如果搜索字段不为空，则进行模糊查询
            criteria.andLike("name","%"+key+"%").orEqualTo("letter",key.toUpperCase());
        }

        if (StringUtils.isNotBlank(sortBy)) {
            //如果排序字段不为空，则进行排序
            String orderByClause = sortBy+(desc?" DESC":" ASC");
            example.setOrderByClause(orderByClause);
        }
        //查询符合条件的数据,page类比pageinfo封装的对象更多
        Page<Brand> pageInfo = (Page<Brand>) brandMapper.selectByExample(example);
        return new PageResult<>(pageInfo.getTotal(),pageInfo);
    }

    //保存新增分类,添加事务管理机制
    @Transactional
    public void saveBrand(Brand brand, List<Long> cids) {
        //新增品牌信息
        this.brandMapper.insertSelective(brand);
        //新增 品牌和分类的中间表
        //cids.forEach( cid -> this.brandMapper.insertCategoryandBrand(cid,brand.getId()));
        for (Long cid : cids) {
            this.brandMapper.insertCategoryandBrand(cid,brand.getId());
        }
    }
    //修改分类资源
    @Transactional
    public void editBrand(Brand brand, List<Long> cids) {
        //修改品牌信息
        this.brandMapper.updateByPrimaryKeySelective(brand);
        //修改 品牌和分类的中间表
        this.brandMapper.delBrand(brand.getId());
        for (Long cid : cids) {
            this.brandMapper.editCategoryandBrand(cid,brand.getId());
        }
    }
    //删除品牌
    @Transactional
    public void delBrand(Long bid) {
        //删除品牌表内的信息
        this.brandMapper.deleteByPrimaryKey(bid);
        //删除中间表的相应信息
        this.brandMapper.delBrand(bid);
    }
    //查询商品的品牌信息
    public Brand queryBrandByBid(Long brandId) {
        Brand brand = this.brandMapper.selectByPrimaryKey(brandId);
        return brand;
    }
    //新增商品时，查询所属分类的品牌信息
    public List<Brand> queryBrandByCategory(Long cid) {
        List<Brand> list = this.brandMapper.queryBrandByCategory(cid);
        return list;
    }

    //根据品牌的id查询数据
    public List<Brand> queryBrandByIds(List<Long> ids) {
        return this.brandMapper.selectByIdList(ids);
    }
}
